@echo off
chcp 65001 >nul
setlocal enabledelayedexpansion

:: PPH系统内存监控和清理脚本
:: 手动执行内存优化和监控

echo ========================================
echo PPH Memory Monitor and Cleanup
echo ========================================
echo.

set "DEPLOY_DIR=%~dp0.."

echo [INFO] PPH Memory Monitor
echo [INFO] Deploy directory: %DEPLOY_DIR%
echo.

:: 显示当前内存使用情况
echo [STEP 1] Current Memory Usage
echo ========================================

echo [INFO] System memory status:
wmic OS get TotalVisibleMemorySize,FreePhysicalMemory /format:table

echo.
echo [INFO] Node.js processes memory usage:
for /f "tokens=1,2,5" %%a in ('tasklist /fi "imagename eq node.exe" /fo table ^| findstr /v "Image"') do (
    if not "%%a"=="INFO:" (
        echo Process: %%a, PID: %%b, Memory: %%c
    )
)

echo.
echo [INFO] PM2 processes status:
pm2 list 2>nul || echo PM2 not available

echo.

:: 检查内存使用是否过高
echo [STEP 2] Memory Usage Analysis
echo ========================================

:: 获取系统总内存和可用内存
for /f "tokens=2" %%a in ('wmic OS get TotalVisibleMemorySize /value ^| findstr "="') do set TOTAL_MEMORY=%%a
for /f "tokens=2" %%a in ('wmic OS get FreePhysicalMemory /value ^| findstr "="') do set FREE_MEMORY=%%a

if defined TOTAL_MEMORY if defined FREE_MEMORY (
    set /a USED_MEMORY=%TOTAL_MEMORY% - %FREE_MEMORY%
    set /a MEMORY_PERCENT=%USED_MEMORY% * 100 / %TOTAL_MEMORY%
    
    echo [INFO] Total Memory: !TOTAL_MEMORY! KB
    echo [INFO] Used Memory: !USED_MEMORY! KB
    echo [INFO] Free Memory: !FREE_MEMORY! KB
    echo [INFO] Memory Usage: !MEMORY_PERCENT!%%
    
    if !MEMORY_PERCENT! GTR 80 (
        echo [WARNING] High memory usage detected: !MEMORY_PERCENT!%%
        set HIGH_MEMORY=1
    ) else (
        echo [OK] Memory usage is normal: !MEMORY_PERCENT!%%
        set HIGH_MEMORY=0
    )
) else (
    echo [WARNING] Could not determine memory usage
    set HIGH_MEMORY=0
)

echo.

:: 清理选项菜单
echo [STEP 3] Cleanup Options
echo ========================================
echo.
echo Available cleanup options:
echo 1. Quick cleanup (temp files, logs)
echo 2. Full cleanup (cache, temp, logs, npm)
echo 3. Emergency cleanup (force GC, restart services)
echo 4. Memory report only
echo 5. Start automatic memory optimizer
echo 6. Stop automatic memory optimizer
echo 0. Exit
echo.

if "%HIGH_MEMORY%"=="1" (
    echo [RECOMMENDATION] High memory usage detected. Recommend option 2 or 3.
)

set /p "choice=Select option (0-6): "

if "%choice%"=="1" goto :quick_cleanup
if "%choice%"=="2" goto :full_cleanup
if "%choice%"=="3" goto :emergency_cleanup
if "%choice%"=="4" goto :memory_report
if "%choice%"=="5" goto :start_optimizer
if "%choice%"=="6" goto :stop_optimizer
if "%choice%"=="0" goto :exit
goto :invalid_choice

:quick_cleanup
echo.
echo [STEP 4] Quick Cleanup
echo ========================================

echo [INFO] Cleaning temporary files...
if exist "%DEPLOY_DIR%\app\backend\uploads\temp" (
    del /q "%DEPLOY_DIR%\app\backend\uploads\temp\*.*" 2>nul
    echo [OK] Temporary files cleaned
) else (
    echo [INFO] No temp directory found
)

echo [INFO] Cleaning old log files (older than 7 days)...
forfiles /p "%DEPLOY_DIR%\app\logs" /s /m *.log /d -7 /c "cmd /c del @path" 2>nul
echo [OK] Old log files cleaned

echo [INFO] Flushing DNS cache...
ipconfig /flushdns >nul 2>&1
echo [OK] DNS cache flushed

goto :cleanup_complete

:full_cleanup
echo.
echo [STEP 4] Full Cleanup
echo ========================================

echo [INFO] Performing full system cleanup...

:: 清理npm缓存
echo [INFO] Cleaning npm cache...
npm cache clean --force >nul 2>&1
echo [OK] npm cache cleaned

:: 清理临时文件
echo [INFO] Cleaning temporary files...
if exist "%DEPLOY_DIR%\app\backend\uploads\temp" (
    del /q "%DEPLOY_DIR%\app\backend\uploads\temp\*.*" 2>nul
)
del /q "%TEMP%\*.*" 2>nul
echo [OK] Temporary files cleaned

:: 清理日志文件
echo [INFO] Cleaning old log files...
forfiles /p "%DEPLOY_DIR%\app\logs" /s /m *.log /d -7 /c "cmd /c del @path" 2>nul
echo [OK] Log files cleaned

:: 清理系统缓存
echo [INFO] Cleaning system caches...
ipconfig /flushdns >nul 2>&1
echo [OK] System caches cleaned

:: 运行内存优化器
echo [INFO] Running memory optimizer...
cd /d "%DEPLOY_DIR%"
node scripts\memory-optimizer.cjs --once 2>nul || echo [WARNING] Memory optimizer failed

goto :cleanup_complete

:emergency_cleanup
echo.
echo [STEP 4] Emergency Cleanup
echo ========================================

echo [WARNING] This will restart all PPH services!
set /p "confirm=Continue? (y/N): "
if /i not "%confirm%"=="y" goto :exit

echo [INFO] Stopping PPH services...
pm2 stop all >nul 2>&1

echo [INFO] Performing emergency cleanup...

:: 强制终止Node.js进程
echo [INFO] Force killing Node.js processes...
taskkill /f /im node.exe >nul 2>&1

:: 清理所有缓存
echo [INFO] Cleaning all caches and temp files...
npm cache clean --force >nul 2>&1
del /q "%TEMP%\*.*" 2>nul
if exist "%DEPLOY_DIR%\app\backend\uploads\temp" (
    del /q "%DEPLOY_DIR%\app\backend\uploads\temp\*.*" 2>nul
)

:: 清理内存
echo [INFO] Clearing system memory...
ipconfig /flushdns >nul 2>&1

:: 等待系统稳定
echo [INFO] Waiting for system to stabilize...
timeout /t 5 /nobreak >nul

:: 重启服务
echo [INFO] Restarting PPH services...
pm2 start "%DEPLOY_DIR%\config\ecosystem.config.cjs" --env production >nul 2>&1

echo [OK] Emergency cleanup completed

goto :cleanup_complete

:memory_report
echo.
echo [STEP 4] Memory Report
echo ========================================

echo [INFO] Generating detailed memory report...

echo.
echo === System Memory ===
wmic OS get TotalVisibleMemorySize,FreePhysicalMemory /format:table

echo.
echo === Process Memory ===
tasklist /fi "imagename eq node.exe" /fo table

echo.
echo === PM2 Status ===
pm2 list 2>nul || echo PM2 not available

echo.
echo === Disk Usage ===
dir "%DEPLOY_DIR%" | findstr "可用字节\|bytes free"

goto :exit

:start_optimizer
echo.
echo [STEP 4] Start Memory Optimizer
echo ========================================

echo [INFO] Starting automatic memory optimizer...
pm2 start pph-memory-optimizer 2>nul || echo [WARNING] Memory optimizer may already be running

pm2 list | findstr "pph-memory-optimizer"
goto :exit

:stop_optimizer
echo.
echo [STEP 4] Stop Memory Optimizer
echo ========================================

echo [INFO] Stopping automatic memory optimizer...
pm2 stop pph-memory-optimizer >nul 2>&1
pm2 delete pph-memory-optimizer >nul 2>&1

echo [OK] Memory optimizer stopped
goto :exit

:cleanup_complete
echo.
echo [STEP 5] Post-Cleanup Status
echo ========================================

echo [INFO] Checking memory usage after cleanup...
timeout /t 3 /nobreak >nul

for /f "tokens=2" %%a in ('wmic OS get FreePhysicalMemory /value ^| findstr "="') do set NEW_FREE_MEMORY=%%a
if defined NEW_FREE_MEMORY if defined FREE_MEMORY (
    set /a MEMORY_FREED=!NEW_FREE_MEMORY! - !FREE_MEMORY!
    if !MEMORY_FREED! GTR 0 (
        set /a MEMORY_FREED_MB=!MEMORY_FREED! / 1024
        echo [OK] Memory freed: !MEMORY_FREED_MB! MB
    ) else (
        echo [INFO] Memory usage unchanged
    )
)

echo [INFO] Current PM2 status:
pm2 list 2>nul || echo PM2 not available

echo.
echo [OK] Cleanup completed successfully!
goto :exit

:invalid_choice
echo [ERROR] Invalid choice. Please select 0-6.
timeout /t 2 /nobreak >nul
goto :exit

:exit
echo.
echo ========================================
echo Memory Monitor Session Ended
echo ========================================
echo.
echo Tips for memory management:
echo - Run this script regularly (weekly recommended)
echo - Monitor memory usage with: pm2 monit
echo - Use option 5 to enable automatic optimization
echo - Check logs in: app\logs\
echo.

pause
